<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>绩效</title>
    <link rel="stylesheet" th:href="@{/static/plugins/layui-v2.4.5/layui/css/layui.css}" href="//res.layui.com/layui/dist/css/layui.css?t=1551352891272" media="all">
    <style>
        body {
            margin: 10px;
        }
    </style>
</head>
<body>

<table class="layui-hide" id="demo" lay-filter="test"></table>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<input type="hidden" th:value="${time}" id="time_hidden"/>
<script src="http://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script>

<script th:src="@{/static/plugins/layui-v2.4.5/layui/layui.js}" src="//res.layui.com/layui/dist/layui.js?t=1551352891272"></script>
<script th:inline="javascript">


    layui.config({
        version: '1551352891272' //为了更新 js 缓存，可忽略
    });

    layui.use(['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element', 'slider'], function () {
        var laydate = layui.laydate //日期
            , laypage = layui.laypage //分页
            , layer = layui.layer //弹层
            , table = layui.table //表格
            , carousel = layui.carousel //轮播
            , upload = layui.upload //上传
            , element = layui.element //元素操作
            , slider = layui.slider //滑块

        //向世界问个好
        layer.msg('欢迎你，李嘉诚！');

        //监听Tab切换
        element.on('tab(demo)', function (data) {
            layer.tips('切换了 ' + data.index + '：' + this.innerHTML, this, {
                tips: 1
            });
        });

        //执行一个 table 实例
        table.render({
            elem: '#demo'
            , height: 420
            , url: '/performance/list?time=' + $("#time_hidden").val() //数据接口
            , title: '绩效表'
            , page: true //开启分页
            , toolbar: '<div class="layui-table-tool-temp">' +
                '<div class="layui-inline" lay-event="add">' +
                '<i class="layui-icon layui-icon-add-1"></i>' +
                '</div>' +
                '<div class="layui-inline" lay-event="delete">' +
                '<i class="layui-icon layui-icon-delete"></i></div>' +
                '<div class="layui-inline" lay-event="output">' +
                '<i class="layui-icon layui-icon-chart-screen"></i></div>' +
                '<div class="layui-inline">' +
                '<div class="layui-input-inline">\n' +
                '        <input type="text" class="layui-input" id="yearMonth" placeholder="当前月" lay-key="4">\n' +
                '      </div>' +
                '</div>'//开启工具栏，此处显示默认图标，可以自定义模板，详见文档
            , totalRow: true //开启合计行
            , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , cols: [[ //表头
                {type: 'checkbox', fixed: 'left'}
                , {field: 'id', title: 'ID', sort: true, fixed: 'left', totalRowText: '合计：'}
                , {field: 'userName', title: '姓名', sort: true, edit: 'text'}
                , {field: 'performanceDate', title: '日期', sort: true, edit: 'text'}
                , {field: 'number', title: '编号', sort: true, edit: 'text'}
                , {field: 'companyName', title: '公司', sort: true, edit: 'text'}
                , {field: 'amount', title: '绩效', sort: true, totalRow: true, edit: 'text'}
            ]]
            , defaultToolbar: ['filter', 'exports', 'print']
        });

        function verifyAmount(amount) {
            var regAmount = /^[0-9]*$/;
            if (!verifyNotNull(amount) || !regAmount.test(amount)) {
                return false;
            }
            return true;
        }

        function verifyDate(date) {
            var regDate = /(\d{1,2})$/;
            if (!verifyNotNull(date) || !regDate.test(date) || date > 31) {
                return false;
            }
            return true;
        }

        //监听单元格编辑
        table.on('edit(test)', function (obj) {
            var value = obj.value //得到修改后的值
                , data = obj.data //得到所在行所有键值
                , field = obj.field; //得到字段
            console.log('[ID: ' + data.id + '] ' + field + ' 字段更改为：' + value);

            var regAmount = /^[0-9]*$/;
            var regDate = /^(\d{1,4})(-)(\d{1,2})\2(\d{1,2})$/;

            if (!regAmount.test(data.amount)) {
                layer.msg('[ID: ' + data.id + '] ' + '金额格式有误');
                return;
            }
            if (!regDate.test(data.performanceDate)) {
                layer.msg('[ID: ' + data.id + '] ' + '日期格式有误');
                return;
            }
            $.ajax({
                type: "post",
                url: "/performance/edit",
                dataType: "json",
                data: {
                    "id": data.id,
                    "userName": data.userName,
                    "companyName": data.companyName,
                    "number": data.number,
                    "performanceDate": data.performanceDate,
                    "amount": data.amount
                },
                success: function (obj) {
                    if (obj.code == '0') {
                        layer.msg('修改成功！');
                    } else {
                        layer.msg(obj.msg);
                    }
                },
                error: function () {
                    layer.msg("网络错误！");

                }
            })

        });

        //监听头工具栏事件
        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id)
                , data = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                case 'add':
                    add();
                    break;
                case 'update':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else if (data.length > 1) {
                        layer.msg('只能同时编辑一个');
                    } else {
                        layer.alert('编辑 [id]：' + checkStatus.data[0].id);
                    }
                    break;
                case 'delete':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else {
                        del(data);
                    }
                    break;
                case 'output':
                    layer.msg('正在导出，请稍后。。。');
                    location.href = "/performance/output?time=" + $("#time_hidden").val();
                    break;
            }
            ;
        });

        function del(data) {
            layer.confirm("确认删除？", function () {
                $.ajax({
                    type: "post",
                    url: "/performance/del",
                    dataType: "json",
                    data: {
                        "data": JSON.stringify(data),
                    },
                    success: function (obj) {
                        if (obj.code == '0') {
                            layer.confirm("删除成功!", function () {
                                location.reload();
                            });
                        } else {
                            layer.msg(obj.msg);
                        }
                    },
                    error: function () {
                        layer.msg("网络错误！");

                    }
                });
            });

        }

        function add() {
            layer.prompt({title: '姓名', formType: 0}, function (name, index) {
                if (verifyNotNull(name)) {
                    layer.close(index);
                    layer.prompt({title: '公司', formType: 0}, function (company, index) {
                        if (verifyNotNull(company)) {
                            layer.close(index);
                            layer.prompt({title: '绩效', formType: 0}, function (amount, index) {
                                if (verifyAmount(amount)) {
                                    layer.close(index);
                                    layer.prompt({title: '编号', formType: 0}, function (number, index) {
                                        layer.close(index);
                                        layer.prompt({title: '日期', formType: 0}, function (date, index) {
                                            if (verifyDate(date)) {
                                                layer.close(index);
                                                $.ajax({
                                                    type: "post",
                                                    url: "/performance/add",
                                                    dataType: "json",
                                                    data: {
                                                        "userName": name,
                                                        "companyName": company,
                                                        "number": number,
                                                        "performanceDate": ($("#yearMonth").val() == '' ? getCurrentYearMonth() : $("#yearMonth").val()) + '-' + (date < 10 ? "0" + date : date),
                                                        "amount": amount
                                                    },
                                                    success: function (obj) {
                                                        if (obj.code == '0') {
                                                            layer.confirm('新增成功！', function () {
                                                                location.reload();
                                                            });
                                                        } else {
                                                            layer.msg(obj.msg);
                                                        }
                                                    },
                                                    error: function () {
                                                        layer.msg("网络错误！");

                                                    }
                                                });
                                            } else {
                                                layer.msg("日期格式有误！");
                                            }
                                        });
                                    });
                                } else {
                                    layer.msg("绩效格式有误！");
                                }
                            });
                        } else {
                            layer.msg("公司不能为空！");
                        }
                    });
                } else {
                    layer.msg("姓名不能为空！");
                }
            });


        }

        function verifyNotNull(str) {
            if (str == null || str == '' || str.length == 0) {
                return false;
            }
            return true;
        }

        //监听行工具事件
        table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'detail') {
                layer.msg('查看操作');
            } else if (layEvent === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构
                    layer.close(index);
                    //向服务端发送删除指令
                });
            } else if (layEvent === 'edit') {
                layer.msg('编辑操作');
            }
        });


        //分页
        laypage.render({
            elem: 'pageDemo' //分页容器的id
            , count: 100 //总页数
            , skin: '#1E9FFF' //自定义选中色值
            //,skip: true //开启跳页
            , jump: function (obj, first) {
                if (!first) {
                    layer.msg('第' + obj.curr + '页', {offset: 'b'});
                }
            }
        });

        laydate.render({
            elem: '#yearMonth'
            , type: 'month'
            , value: $("#time_hidden").val()
            , isInitValue: true
            , change: function (value, date) {
                layer.msg('你选择的日期是：' + value + '<br><br>获得的对象是' + JSON.stringify(date));
                location.href = "/index?time=" + value;
            }
        });

        slider.render({
            elem: '#sliderDemo'
            , input: true //输入框
        });

    });

    function getCurrentYearMonth() {
        var date = new Date;
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        month = (month < 10 ? "0" + month : month);
        return year + "-" + month;
    }

</script>
</body>
</html>
